package com.wanmei.service.Impl;

import com.wanmei.exception.WanmeiException;
import com.wanmei.mapper.*;
import com.wanmei.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmei.service.ProductService;
import com.wanmei.util.ImageUtil;
import com.wanmei.util.VolidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    ProductkuidMapper productkuidMapper;
    @Autowired
    OrderdetailMapper orderdetailMapper;
    @Autowired
    private ProductpicMapper productpicMapper;

    /**
     * @param pageNum
     * @param pageSize
     * @return
     * @description 返回所有产品信息
     */
    public PageInfo<Object> showProduct(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Object> list = productMapper.selectAll();
        PageInfo<Object> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * @param pageNum
     * @param pageSize
     * @return
     * @description 返回所有产品类别信息
     */
    public PageInfo<Category> showProductCategory(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> list = categoryMapper.selectAll();
        PageInfo<Category> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * @param product
     * @return
     * @description 添加产品信息
     */
    public int productAddService(Product product) {
        return productMapper.insert(product);
    }

    /**
     * @param pid
     * @return
     * @description 根据pid返回产品信息
     */

    public List<Product> selectProductInfoByPid(Integer pid) {
        return productMapper.selectProductInfoByPid(pid);
    }

    /**
     * @param pid
     * @return
     * @description 根据pid返回产品库存信息
     */
    public List<Productkuid> selectProductKuidByPid(Integer pid) {
        return productkuidMapper.selectProductKuidByPid(pid);
    }

    /**
     * @param
     * @return
     * @description 返回产品库存信息
     */
    public List<Object> selectProductKuid() {
        return productkuidMapper.selectAll();
    }


    /**
     * @param product
     * @return
     * @description 更新产品信息, 更新库存信息
     */

    public int updateProductInfo(Product product, String[] vids, String[] storenums, String realPath) throws WanmeiException {

        //对输入的字段进行判断
        if (product.getCid() == null) {
            throw new WanmeiException(Exception_Msg.ERROR_300008);
        }
        if (product.getPname().length() > 30) {
            throw new WanmeiException(Exception_Msg.ERROR_300004);
        }
        if (product.getPpoint().length() > 100) {
            throw new WanmeiException(Exception_Msg.ERROR_300006);
        }
        if (product.getInformation().length() > 500) {
            throw new WanmeiException(Exception_Msg.ERROR_300007);
        }

        for (int i = 0; i < vids.length; i++) {
            Productkuid productkuid = new Productkuid();
            productkuid.setPid(product.getPid());
            productkuid.setStorenum(Integer.parseInt(storenums[i]));
            if (!VolidatorUtil.isNumber(storenums[i])) {
                throw new WanmeiException(Exception_Msg.ERROR_300009);
            }
            productkuid.setVid(Integer.parseInt(vids[i]));
            int isSuccess = productkuidMapper.updateByPidAndVid(productkuid);
        }

        int isSave = productMapper.updateProductInfo(product);
        //如果产品更新图片
        if (product.getImgurl() != null && product.getImgurl() != "") {

            String imgurl = product.getImgurl();
            String extensionName = imgurl.substring(imgurl.lastIndexOf(".") + 1);
            String newHeadName = ImageUtil.getImageNewName();
            String fileName = newHeadName + "." + extensionName;
            String path = ImageUtil.REAL_PATH;
            try {
                File file = new File(realPath + imgurl);
                File result = new File(path + fileName);
                InputStream is = new FileInputStream(file);
                OutputStream os = new FileOutputStream(result);
                System.out.println("");
                int in = is.available();
                int len = 0;
                byte[] buffer = new byte[in];
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.flush();
                os.close();
                is.close();
                Productpic productpic = new Productpic();
                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format.format(date);
                productpic.setAdduser("admin");
                productpic.setPicurl(path + fileName);
                productpic.setPid(product.getPid());
                Productpic productpic1 = productpicMapper.selectOnePicUrl(product.getPid());
                int isSuccess;
                if (productpic1 != null) {
                    productpic.setModifytime(nowTime);
                    isSuccess = productpicMapper.updateByPrimaryKeySelective(productpic);
                } else {
                    productpic.setAddtime(nowTime);
                    isSuccess = productpicMapper.insertSelective(productpic);
                }
                return isSuccess;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }
        return isSave;

    }

    /**
     * @param pid
     * @return
     * @description 根据Pid删除产品信息
     */

    public int deleteProductByPid(Integer pid) {
        //将订单详情的pid置空
        orderdetailMapper.updateByPid(pid); //1
        //先删除库存
        productkuidMapper.deleteByPid(pid);
        //删除图片
        productpicMapper.deleteByPID(pid);
        //删除产品
        return productMapper.deleteProductByPid(pid);

    }

    /**
     * 通过产品的pid获取图片信息
     */

    public Product selectByPrimaryKey(Integer pid) {
        return productMapper.selectByPrimaryKey(pid);
    }

    /**
     * 正序模糊分页查询
     */
    public PageInfo<Product> getProductByFuzzy(String likeValue, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> list = productMapper.getProductByFuzzy(likeValue);
        PageInfo<Product> info = new PageInfo<>(list);
        return info;
    }

    /**
     * 倒序分页查询
     */
    public PageInfo<Object> showProductDESC(int pageNum, int pageSize) {
        String order = "PID DESC";
        PageHelper.startPage(pageNum, pageSize, order);
        List<Object> list = productMapper.selectAll();
        PageInfo<Object> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 添加商品字段
     *
     * @param product
     * @param realPath
     * @return
     * @throws WanmeiException
     */
    public int saveProductInfo(Product product, String realPath) throws WanmeiException {
        //对输入的字段进行判断
        if (product.getCid() == null) {
            throw new WanmeiException(Exception_Msg.ERROR_300008);
        }
        if (product.getPname().length() > 30) {
            throw new WanmeiException(Exception_Msg.ERROR_300004);
        }
        if (product.getPpoint().length() > 100) {
            throw new WanmeiException(Exception_Msg.ERROR_300006);
        }
        if (product.getInformation().length() > 500) {
            throw new WanmeiException(Exception_Msg.ERROR_300007);
        }
        //产品插入成功后插入产品图片
        int isSave = productMapper.insertSelective(product);
        if (product.getImgurl() != null && product.getImgurl() != "") {
            String imgurl = product.getImgurl();
            String extensionName = imgurl.substring(imgurl.lastIndexOf(".") + 1);
            String newHeadName = ImageUtil.getImageNewName();
            String fileName = newHeadName + "." + extensionName;
            String path = ImageUtil.REAL_PATH;
            try {
                File file = new File(realPath + imgurl);
                File result = new File(path + fileName);
                InputStream is = new FileInputStream(file);
                OutputStream os = new FileOutputStream(result);
                int in = is.available();
                int len = 0;
                byte[] buffer = new byte[in];
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.flush();
                os.close();
                is.close();
                Productpic productpic = new Productpic();
                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format.format(date);
                productpic.setAddtime(nowTime);
                productpic.setAdduser("admin");
                productpic.setPicurl(path + fileName);
                productpic.setPid(product.getPid());
                int isSuccess = productpicMapper.insertSelective(productpic);
                return isSuccess;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }
        return isSave;
    }

    public List<Product> findAll(){
        return  productMapper.findAll();
    }

}
